import 'package:chathouse/constant/app_constant.dart';
import 'package:chathouse/constant/my_color.dart';
import 'package:chathouse/pages/login/register_success.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:chathouse/widgets/form_widgets/form_widgets.dart';
import 'package:chathouse/widgets/my_input_widget.dart';
import 'package:chathouse/widgets/time_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:chathouse/util/base_utils.dart';
import '../../model/response_bean.dart';
import '../../net/Apis.dart';
import '../../public/Global.dart';
import '../../public/Obj.dart';
import '../../util/SpUtil.dart';
import '../../util/font_utils.dart';
import '../../util/toast_util.dart';
import 'package:get/get.dart';

//驗證碼校驗頁
class SmsCheckPage extends StatefulWidget {
  String? name;
  String? phone;
  String? email;
  String? pwd;
  String? area;
  String? userName;
  String? referencePhone;
  SmsCheckPage(this.name, this.phone, this.email, this.pwd, this.area,this.referencePhone,
      {Key? key})
      : super(key: key) {
    userName = (phone ?? "").isNotEmpty ? (area! + phone!) : email;
  }

  @override
  State<SmsCheckPage> createState() => _SmsCheckPageState();
}

class _SmsCheckPageState extends State<SmsCheckPage> {
  String title = "";
  String title2 = "";

  bool canClickSure = false;
  TextEditingController codeEditingController = TextEditingController();
  @override
  void initState() {
    super.initState();
    title = (widget.phone ?? "").isEmpty ? "EMAIL 電郵認證" : "SMS 電話認證";
    title2 = (widget.phone ?? "").isEmpty
        ? "請輸入送至 ${widget.email} 的驗證碼"
        : "請輸入送至 +${widget.area} ${widget.phone} 的驗證碼";
    getAuthCode();
    codeEditingController.addListener(() {
      setState(() {
        canClickSure = codeEditingController.text.isNotEmpty;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    codeEditingController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(leading: Container()),
      body: ListView(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                title,
                textAlign: TextAlign.left,
                style: getTextStyle(32.sp,
                    fontType: FontType.MID, color: Colors.black),
              ).setContainer(
                  width: double.infinity, margin: EdgeInsets.only(top: 4.w)),
              MyInputWidget(
                title: title2,
                controller: codeEditingController,
              ).setContainer(margin: EdgeInsets.only(top: 40.w)),
              TimeButton(
                () {
                  getAuthCode();
                },
                initStart: true,
              ).setContainer(width: 170.w, margin: EdgeInsets.only(top: 20.w)),
              FormWidgets.getTextButton(
                      "確定",
                      MyColors.green_69157154,
                      enable: canClickSure)
                  .setContainer(
                      margin:
                          EdgeInsets.only(left: 60.w, right: 60.w, top: 98.w))
                  .setOnClickListener(() {
                register();
              })
            ],
          ).setContainer(padding: EdgeInsets.symmetric(horizontal: 28.w))
        ],
      ).setContainer(color: Colors.white),
    );
  }

  void getAuthCode() {
    if ((widget.phone ?? "").isNotEmpty) {
      ResponseBean result;
      Apis.getSmsCode({"phone": widget.phone, "countryCode": widget.area})
          .then((response) => {
                Obj.dismissLoading(),
                result = ResponseBean.fromJson(response?.data ?? {}),
                if (result.isRequestSuccess)
                  {
                    // codeEditingController.text = result.msg ?? "",
                    ToastUtil.showToast("SMS已發送"),
                  }
              })
          .catchError((error) => {});
    } else {
      ResponseBean result;
      Apis.getEmailCode({"email": widget.email})
          .then((response) => {
                Obj.dismissLoading(),
                result = ResponseBean.fromJson(response?.data ?? {}),
                if (result.isRequestSuccess)
                  {
                    // codeEditingController.text = result.msg ?? "",
                    ToastUtil.showToast("電郵已發送"),
                  }
              })
          .catchError((error) => {});
    }
  }

  void register() {
    if (!canClickSure) return;
    var params = {
      "membersName": widget.name,
      "memberPassword": widget.pwd,
      "rawPassword": widget.pwd,
      "code": codeEditingController.text,
      "membersIdentity": AppConstant.userRole == UserRole.c ? "1" : "2",
      "referencePhone":widget.referencePhone
    };
    if ((widget.phone ?? "").isNotEmpty) {
      params["membersPhone"] = (widget.area! + widget.phone!);
    }
    if ((widget.email ?? "").isNotEmpty) {
      params["membersEmail"] = widget.email!;
    }
    FocusManager.instance.primaryFocus?.unfocus();
    Obj.showLoading();
    ResponseBean result;
    Apis.userRegister(params)
        .then((response) => {
              Obj.dismissLoading(),
              result = ResponseBean.fromJson(response?.data ?? {}),
              if (result.isRequestSuccess)
                {
                  //註冊成功需要獲取token，調用登陸接口
                  loginAction(widget.pwd!, widget.userName!),
                  Get.to(const RegisterSuccessPage())
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  void loginAction(String pwd, String user) {
    var params = {
      "mark": 1,
      "password": pwd,
      "username": user,
    };
    ResponseBean result;
    Apis.login(params, queryParameters: {
      "Identity": AppConstant.userRole == UserRole.c ? "1" : "2"
    })
        .then((response) => {
              result = ResponseBean.fromJson(response?.data ?? {}),
              if (result.isRequestSuccess)
                {
                  SpUtil.putString(Keys.token, response?.data[Keys.token]),
                  AppConstant.token = response?.data[Keys.token],
                }
            })
        .catchError((error) => {});
  }
}
